package com.springstudy.redisSpring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

/**
 * spring下使用redis
 * 创建连接时需要从RedisConnectionFactory获取
 *
 * @author chenrongrong
 * @since 2020/3/12 16:11
 */
@Configuration
public class RedisConfig  {

    private RedisConnectionFactory connectionFactory = null;

    public RedisConnectionFactory initRedisConnectionFactory() {
        if (this.connectionFactory != null) {
            return this.connectionFactory;
        }
        //jedis配置
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        //设置最大空闲数
        poolConfig.setMaxIdle(30);
        //设置最大连接数
        poolConfig.setMaxTotal(50);
        //设置最大等待毫秒数
        poolConfig.setMaxWaitMillis(2000);
        //使用配置创建Jedis连接工厂
        JedisConnectionFactory connectionFactory = new JedisConnectionFactory(poolConfig);
        //获取单机的Redis配置
        RedisStandaloneConfiguration rsCfg = connectionFactory.getStandaloneConfiguration();

        connectionFactory.setHostName("127.0.0.1");
        connectionFactory.setPassword("123456");

        this.connectionFactory = connectionFactory;
        return connectionFactory;
    }

    //初始化redisTemplate
    @Bean
    public RedisTemplate<Object, Object> initRedisTemplate() {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        //获取RedistTemplate初始化时自动生成的序列化器对象
        RedisSerializer stringRedisSerializer = redisTemplate.getStringSerializer();
        //设置字符串序列化器，使Spring将Redis的key当作字符串处理
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        //redisTemplate.setHashValueSerializer(stringRedisSerializer);
        redisTemplate.setConnectionFactory(initRedisConnectionFactory());

        return redisTemplate;
    }
}
